package com.barneyx.mshinfoplatform.web.common;

import com.barneyx.mshinfoplatform.common.ExResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.Date;

@RestController
@RequestMapping("/api/tool/mail/")
public class MailController {

    @Resource
    private JavaMailSenderImpl javaMailSender;


    @Value("${spring.mail.username}")
    private String sendMailer;


    /**
     * 发送纯文本邮件
     *
     * @param to
     * @param subject
     * @param text
     */
//    public ExResult<?> sendTextMailMessage(String to, String subject, String text){
    @GetMapping("/test")
    public ExResult<?> sendTextMailMessage() {
        String to = "353532415@qq.com";
        String subject = "测试一下";
        String text = "Hello 这个是测试邮件信息主体内容";

        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功：" + sendMailer + "->" + to);
            return ExResult.ofSuccess("发送邮件成功：" + sendMailer + "->" + to);

        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败：" + e.getMessage());
            return ExResult.ofFail("发送邮件失败：" + e.getMessage());
        }

    }
}
